package org.hxzon.util;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

public class ProbabilityUtil {

    public static boolean isWinning(int probability) {
        return new Random().nextInt(100) + 1 <= probability;
    }

    public static String chanceSelect(Map<String, Integer> keyChanceMap) {
        if (keyChanceMap == null || keyChanceMap.size() == 0) {
            return null;
        }

        // split range
        int newValue = 0;
        Map<String, Integer> origKeyChanceMap = keyChanceMap;
        keyChanceMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : origKeyChanceMap.entrySet()) {
            newValue += entry.getValue();
            keyChanceMap.put(entry.getKey(), newValue);
        }
        //last newValue just sumRatio
        // [1 ... sumRatio]
        int rand = new Random().nextInt(newValue) + 1;
        for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {
            if ((rand - entry.getValue()) <= 0) {
                return entry.getKey();
            }
        }

        return null;
    }

    //if ratio is zero,be avlRatio
    public static String chanceSelectAuto(Map<String, Integer> keyChanceMap) {
        if (keyChanceMap == null || keyChanceMap.size() == 0) {
            return null;
        }

        int sumRatio = 0;
        int countFixRatio = 0;
        for (Integer value : keyChanceMap.values()) {
            sumRatio += value;
            countFixRatio += (value > 0 ? 1 : 0);
        }
        //if sumRatio >= 100 ?
        int avlRatio = (100 - sumRatio) / (keyChanceMap.size() - countFixRatio);
        avlRatio = (avlRatio < 0) ? 1 : avlRatio;
        //split range
        Map<String, Integer> origKeyChanceMap = keyChanceMap;
        keyChanceMap = new LinkedHashMap<String, Integer>();
        int newValue = 0;
        for (Map.Entry<String, Integer> entry : origKeyChanceMap.entrySet()) {
            int value = (entry.getValue() > 0) ? entry.getValue() : avlRatio;
            newValue += value;
            keyChanceMap.put(entry.getKey(), newValue);
        }
        //last newValue just sumRatioFinal
        // [1 ... sumRatioFinal]
        int rand = new Random().nextInt(newValue) + 1;
        for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {
            if ((rand - entry.getValue()) <= 0) {
                return entry.getKey();
            }
        }

        return null;
    }

}
